package main

import (
	//"strings"
	"time"
	//"bytes"
	"database/sql"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"log"
)

var db *sql.DB

// 一篇Blog 的结构
type Blog struct {
	id        int64
	title     string
	cid       int64
	content   string
	author    string
	click     int64
	add_time  int64
	status    int64
	recommend int64
	uid       int64
}

func main() {
	db = ConnectDB("root", "", "blog")
	//GetBlogById(24)

	GetBlogsByIds([]string{"19", "21"})

}

//连接数据库
func ConnectDB(user, password, dbName string) *sql.DB {
	//root:12345@localhost/db
	db, err := sql.Open("mysql", user+":"+password+"@/"+dbName)
	if err != nil {
		log.Fatal(err)
		return nil
	}
	return db
}

//查询一条记录
func GetBlogById(id int64) {
	var b Blog
	defer db.Close()
	row := db.QueryRow("select * from blog where id=?", id) //where id in(20,30) 怎么写？
	err := row.Scan(&b.id, &b.title, &b.cid, &b.content, &b.author, &b.click, &b.add_time,
		&b.status, &b.recommend, &b.uid)
	if err != nil {
		log.Fatal("文章不存在")
	}
	fmt.Println(b.id, b.title, unix2time(b.add_time))
}

//查询多条记录
func GetBlogsByIds(ids []string) []Blog {
	var blog Blog
	blogs := make([]Blog, 0)

	rows, err := db.Query("select id,title,add_time from blog where id in (?,?)", ids[0], ids[1])
	if err != nil {
		fmt.Println(err)
		return nil
	}
	defer rows.Close()

	for rows.Next() {
		err := rows.Scan(&blog.id, &blog.title, &blog.add_time)
		if err != nil {
			fmt.Println(err)
			return nil
		}
		blogs = append(blogs, blog)
	}
	fmt.Println("查询到的结果....")
	for _, v := range blogs {
		fmt.Println(v.id, v.title, unix2time(v.add_time))
	}
	return blogs

}

//插入一条记录

//使用事物

//时间戳 转换成指定格式时间
func unix2time(unix int64) string {
	t := time.Unix(unix, 0)
	return t.Format("2006.01.02 15:04:03")
}
